﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using System.Security.Claims;
using TravelServer.DTOs;
using TravelServer.Models;
using TravelServer.Services;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace TravelServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ShoppingCartController : ControllerBase
    {
        private readonly IHttpContextAccessor contextAccessor;
        private readonly ITouristRoutsRepository toursRepository;
        private readonly IMapper mapper;
        private readonly UserManager<AppUser> userManager;

        public ShoppingCartController(IHttpContextAccessor contextAccessor,
            ITouristRoutsRepository toursRepository
            , IMapper mapper)
        {
            this.contextAccessor = contextAccessor;
            this.toursRepository = toursRepository;
            this.mapper = mapper;
        }

        [HttpGet]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> GetShoppingCart()
        {
            //1获取当前用户id
            var userIdClaim = contextAccessor.HttpContext.User?.FindFirst(ClaimTypes.NameIdentifier);

            if (userIdClaim == null)
            {
                // Handle the case where the claim is not found
                return Unauthorized("User ID not found");
            }

            var userId = userIdClaim.Value;
            //2获取购物车
            var shopCart = await toursRepository.GetShoppingCartByUserIdAsync(userId);

            if (shopCart == null)
            {
                return NotFound();
            }

            return Ok(mapper.Map<ShoppingCartDto>(shopCart));

        }

        [HttpPost("AddItem")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> AddShoppingCartItem([FromBody] AddShoppingCartItemDto itemDto)
        {
            //1获取当前用户id
            var userIdClaim = contextAccessor.HttpContext.User?.FindFirst(ClaimTypes.NameIdentifier);
            if (userIdClaim == null)
            {
                return Unauthorized("User ID not found");
            }

            var userId = userIdClaim.Value;
            //2获取购物车
            var shopCart = await toursRepository.GetShoppingCartByUserIdAsync(userId);

            if (shopCart == null)
            {
                return NotFound();
            }

            //3获取旅游路线
            var touristRoute = await toursRepository.GetTouristRouteAsync(itemDto.TouristRouteId);
            if (touristRoute == null)
            {
                return NotFound();
            }

            //创建item
            var line = new LineItem()
            {
                TouristRouteId = itemDto.TouristRouteId,
                ShoppingCartId = shopCart.Id,
                OriginalPrice = touristRoute.OriginalPrice,
                DiscountPresent = touristRoute.DiscountPresent
            };

            shopCart.ShoppingCartlineItems.Add(line);

            await toursRepository.AddShoppingCartItemAsync(line);

            await toursRepository.SaveDataAsync();

            return Ok(mapper.Map<ShoppingCartDto>(shopCart));

        }

        [HttpDelete("DeleteItem/{itemId}")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> DeleteShoppingCartItemById([FromRoute] int itemId)
        {
            var item = await toursRepository.GetShoppingCartItemAsync(itemId);
            if (item == null) { return NotFound(); }
            toursRepository.DeleteShoppingCartItem(item);
            await toursRepository.SaveDataAsync();
            return Ok();
        }

        [HttpDelete("DeleteItems")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> DeleteShoppingCartItemByIds([FromQuery] IEnumerable<int> Ids)
        {
            var items = await toursRepository.GetShoppingCartItemsByIdListAsync(Ids);
            if (items == null || items.Count() == 0) { return NotFound(); };

            toursRepository.DeleteShoppingCartItems(items);
            await toursRepository.SaveDataAsync();
            return Ok();

        }

        [HttpPost("CheckOut")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> CreateOrderFormShoppingCart()
        {
            //1获取当前用户id
            var userIdClaim = contextAccessor.HttpContext.User?.FindFirst(ClaimTypes.NameIdentifier);
            if (userIdClaim == null)
            {
                return Unauthorized("User ID not found");
            }

            var userId = userIdClaim.Value;
            //2获取购物车
            var shopCart = await toursRepository.GetShoppingCartByUserIdAsync(userId);

            if (shopCart == null)
            {
                return NotFound();
            }

            //3创建订单
            var order = new Order()
            {
                Id = Guid.NewGuid(),
                UserId = userId,
                OrderLineItems=shopCart.ShoppingCartlineItems ,
                State = OrderStateEnum.Pending,
                CreateDataUTC = DateTime.UtcNow,
                TransactionMetadata = string.Empty
            };

            //4清空原购物车
            shopCart.ShoppingCartlineItems = null;
            Console.WriteLine("order:"+order.OrderLineItems.Count);
            //Console.WriteLine("shopCart:" + shopCart.ShoppingCartlineItems.Count);
            //5保存order到数据库
            await toursRepository.SaveOrderAsync(order);
            await toursRepository.SaveDataAsync();

           
            return Ok(mapper.Map<OrderDto>(order));
        }
    }
}
